package com.tianyu.inspection.common;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.util.DigestUtils;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Objects;

/**********************************
 * @Author YSW
 * @Description
 * @Date 2020.12.16 - 9:49
 **********************************/

@Slf4j
public class HttpRequest {

    /**
     * Http登录云平台获取 userId utoken 作为获取云盒列表的请求头字段
     *
     * @param host 访问主机
     * @param accessKeyId 访问Key
     * @param accessKeySecret 访问密钥
     * @return
     */
    public static ModelMap yuKongThirdLogin(String host, String accessKeyId, String accessKeySecret) {
        HashMap<String, Object> map = new HashMap<>(2);
        long timeStamp = System.currentTimeMillis();
        map.put("accessKey", accessKeyId);
        map.put("accessKeySecret", accessKeySecret);
        HttpHeaders httpHeaders = new HttpHeaders();
        HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity<>(map, httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        ModelMap resultMap = null;
        try {
            ModelMap result = restTemplate.postForObject(host + "/api/third/user/login", httpEntity, ModelMap.class);
            resultMap = new ModelMap();
            resultMap.addAttribute("state", 0);
            if (result != null && result.get("state").equals(0)) {
                resultMap.addAttribute("state", 1);
                Object respBody = result.get("returnData");
                if (Objects.nonNull(respBody)) {
                    ModelMap modelMap = new ObjectMapper()
                            .convertValue(respBody, ModelMap.class);
                    resultMap.addAllAttributes(modelMap);
                }
            }
        } catch (ResourceAccessException e) {
            log.error("服务端或已关闭，拒绝连接...");
        } catch (RestClientException | IllegalArgumentException e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    public static ModelMap getUserInfoFromYuKong(String host,String token) {
        return ykRequestGet(host + "/api/third/account/info",token,false);
    }

    public static ModelMap getTaskInfoFromYuKong(String host, String token, String taskId) {
        return ykRequestGet(host + "/api/third/task/detail/" + taskId,token,false);
    }

    public static ModelMap getTaskVideoFromYuKong(String host, String token, String taskId) {
        return ykRequestGet(host + "/api/third/task/history/video/" + taskId,token,true);
    }

    public static ModelMap getLiveTaskVideoFromYuKong(String host, String token, String taskId) {
        return ykRequestGet(host + "/api/third/task/live/pull/" + taskId,token,false);
    }

    public static ModelMap getTaskTelemetryFromYuKong(String host, String token, String taskId) {
        return ykRequestGet(host + "/api/third/task/history/track/" + taskId,token,false);
    }


    public static ModelMap ykRequestGet(String url, String token,boolean isArrayResult) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("u-token", token);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        ModelMap resultMap = null;
        try {
            ResponseEntity<ModelMap> request = restTemplate.exchange(url, HttpMethod.GET, requestEntity, ModelMap.class);
            ModelMap result = request.getBody();
            resultMap = new ModelMap();
            resultMap.addAttribute("state", 0);
            if (result != null && result.get("state").equals(0)) {
                resultMap.addAttribute("state", 1);
                Object respBody = result.get("returnData");
                if (Objects.nonNull(respBody)) {
                    if (isArrayResult){
                        JSONArray jsonArray = new ObjectMapper()
                                .convertValue(respBody, JSONArray.class);
                        resultMap.addAttribute("content",jsonArray);
                    }else {
                        ModelMap modelMap = new ObjectMapper()
                                .convertValue(respBody, ModelMap.class);
                        modelMap.remove("state");
                        resultMap.addAllAttributes(modelMap);
                    }
                }
            }
        } catch (ResourceAccessException e) {
            log.error("服务端或已关闭，拒绝连接...");
        } catch (RestClientException | IllegalArgumentException e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    /**
     * Http登录云平台获取 userId utoken 作为获取云盒列表的请求头字段
     *
     * @param boxHost 访问主机
     * @param accessKeyId 访问Key
     * @param accessKeySecret 访问密钥
     * @return
     */
    public static JSONObject cloudPlatformCompanyLogin(String boxHost, String accessKeyId, String accessKeySecret) {
        HashMap<String, Object> map = new HashMap<>(3);
        long timeStamp = System.currentTimeMillis();
        map.put("accessKeyId", accessKeyId);
        map.put("encryptStr", DigestUtils.md5DigestAsHex((accessKeyId + accessKeySecret + timeStamp).getBytes()));
        map.put("timeStamp", timeStamp);
        HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity<>(map);
        RestTemplate restTemplate = new RestTemplate();
        JSONObject jsonObject = null;
        try {
            ModelMap result = restTemplate.postForObject(boxHost + "/eapi/auth/getToken", httpEntity, ModelMap.class);
            jsonObject = new JSONObject();
            jsonObject.put("state", 0);
            if (result != null && result.get("state").equals(0)) {
                jsonObject.put("state", 1);
                Object respBody = result.get("content");
                if (Objects.nonNull(respBody)) {
                    ModelMap modelMap = new ObjectMapper()
                            .convertValue(respBody, ModelMap.class);
                    jsonObject.putAll(modelMap);
                }
            }
        } catch (ResourceAccessException | HttpServerErrorException.BadGateway e) {
            log.error("服务端或已关闭，拒绝连接...");
        } catch (RestClientException | IllegalArgumentException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * Http登录云平台获取 userId utoken 作为获取云盒列表的请求头字段
     *
     * @param boxHost
     * @param name
     * @param password
     * @return
     */
    public static ModelMap cloudPlatformUserLogin(String boxHost, String name, String password) {
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("accountNumber", name);
        map.put("accountCode", password);
        HttpHeaders httpHeaders = new HttpHeaders();
        HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity<>(map, httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        ModelMap result = restTemplate.postForObject(boxHost + "/api/client/login", httpEntity, ModelMap.class);
        ModelMap resultMap = new ModelMap();
        resultMap.addAttribute("state", 0);
        if (Objects.nonNull(result) && result.get("state").equals(0)) {
            resultMap.addAttribute("state", 1);
            Object respBody = result.get("content");
            if (Objects.nonNull(respBody)) {
                ModelMap modelMap = new ObjectMapper()
                        .convertValue(respBody, ModelMap.class);
                resultMap.addAllAttributes(modelMap);
                resultMap.put("companyId",modelMap.get("userId"));
                resultMap.put("accessToken",modelMap.get("utoken"));
            }
        }
        return resultMap;
    }

    /**
     * Http获取云盒列表
     *
     * @param boxHost
     * @param userId
     * @param token
     * @return
     */
    public static ModelMap getBoxListFromCloudPlatform(String boxHost, String userId, String token) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("x-cid", userId);
        httpHeaders.add("x-token", token);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<ModelMap> request = null;
        try {
            request = restTemplate.exchange(boxHost + "/eapi/box/list", HttpMethod.GET, requestEntity, ModelMap.class);
            return request.getBody();
        } catch (ResourceAccessException | HttpServerErrorException e) {
            log.error("服务端或已关闭，拒绝连接...");
        } catch (RestClientException | IllegalArgumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Http获取云盒列表
     *
     * @param boxHost
     * @param userId
     * @param utoken
     * @return
     */
    public static ModelMap getBoxLiveVideoUrl(String boxHost, String userId, String utoken, String boxSn) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("x-cid", userId);
        httpHeaders.add("x-token", utoken);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<ModelMap> request = restTemplate.exchange(boxHost + "/eapi/box/liveUrl/" + boxSn, HttpMethod.GET, requestEntity, ModelMap.class);
        return request.getBody();
    }

    public static ModelMap getTaskInfoFromCloudPlatform(String boxHost, String userId, String utoken, int taskId) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("x-cid", userId);
        httpHeaders.add("x-token", utoken);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        ModelMap resultMap = null;
        try {
            ResponseEntity<ModelMap> request = restTemplate.exchange(boxHost + "/eapi/box/history/" + taskId, HttpMethod.GET, requestEntity, ModelMap.class);
            ModelMap result = request.getBody();
            resultMap = new ModelMap();
            resultMap.addAttribute("state", 0);
            if (result != null && result.get("state").equals(0)) {
                resultMap.addAttribute("state", 1);
                Object respBody = result.get("content");
                if (Objects.nonNull(respBody)) {
                    ModelMap modelMap = new ObjectMapper()
                            .convertValue(respBody, ModelMap.class);
                    resultMap.addAllAttributes(modelMap);
                }
            }
        } catch (ResourceAccessException e) {
            log.error("服务端或已关闭，拒绝连接...");
        } catch (RestClientException | IllegalArgumentException e) {
            e.printStackTrace();
        }
        return resultMap;
    }
}